<script setup lang='ts'>
import { useAccountAudit, useAccountDetail, useGetAllSupplierTree, useGetEnterpriseType } from '@fl/api/man-api'
import { SearchForm } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { ElCard } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { useRoute, useRouter } from 'vue-router'

const { params } = useRoute()
const { back } = useRouter()

const { data: supplierTree } = useGetAllSupplierTree()
const key = ref(1)
const id = computed(() => {
    return params.id
})

const { data, isLoading } = useAccountDetail(id)

const { isPending, mutate } = useAccountAudit()
const state = ref<any>({
    authorizationLetterList: [],
    businessLicenseList: [],
    faceSignRecordList: [],
})

const type = computed(() => Number(state.value.enterpriseType) + 1)

const { data: enterpriseTypeList } = useGetEnterpriseType(type)

const authenticationAmountEunm = {
    0: '未打款',
    1: '已打款',
}

const showReason = computed(() => data.value?.enterpriseAuditStatus === 2)

const disabled = computed(() => true)

const finalGroup: any = computed(() => {
    return [
        {
            columns: [
                {

                    label: '账号',
                    prop: 'userNo',
                    valueType: 'text',
                },
                {
                    label: '来源',
                    prop: 'source',
                    valueType: 'text',
                },
                {
                    label: '渠道',
                    prop: 'channel',
                    valueType: 'text',
                },
                {
                    label: '注册时间',
                    prop: 'accountCreateTime',
                    valueType: 'text',
                },
                {
                    label: '认证方式',
                    prop: 'authenticationType',
                    valueType: 'text',
                },
                {
                    label: '认证金额',
                    prop: 'authenticationAmount',
                    valueType: 'text',
                },
            ],
            title: '账号信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: computed(() => {
                        return Number(state.value.enterpriseType) === 0 ? `采购商类型` : `供应商类型`
                    }),

                    options: computed(() => {
                        return enterpriseTypeList.value || []
                    }),
                    prop: 'enterpriseSecondType',
                    valueType: 'select',
                    width: 120,
                },
                {

                    fieldProps: {
                        disabled,
                        props: {
                            multiple: true,

                        },
                        showAllLevels: false,
                    },
                    hideInForm: computed(() => !(Number(state.value.enterpriseType) === 1)),
                    label: '供应商类别',
                    options: computed(() => {
                        return supplierTree.value || []
                    }),
                    prop: 'supplyCat',
                    valueType: 'cascader',
                    width: 120,
                },

            ],
            title: '机构类型',
        },
        {
            columns: [
                {
                    label: '公司名称',
                    prop: 'companyName',
                    valueType: 'text',
                },
                {
                    label: '法定代表人',
                    prop: 'legalRepresentative',
                    valueType: 'text',

                },
                {
                    label: '统一社会信用代码',
                    prop: 'unifiedSocialCreditCode',
                    valueType: 'text',
                    labelWidth: 140,
                },
                {
                    colProps: {
                        span: 16,
                    },
                    label: '注册地址',
                    prop: 'registeredAddress',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    label: '联系电话',
                    prop: 'contactPhone',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '企业LOGO',
                    prop: 'logo',

                },
            ],
            hideInGroup: false,
            title: '企业认证信息',
        },
        {
            columns: [
                {
                    label: '法人姓名',
                    prop: 'legalPersonName',
                    valueType: 'text',
                },
                {
                    label: '身份证',
                    prop: 'legalPersonIdCardNo',
                    valueType: 'text',
                },
                {
                    label: '手机号',
                    prop: 'legalPersonMobile',
                    valueType: 'text',
                },
            ],
            title: '法人信息',
        },
        {
            columns: [
                {
                    label: '开户名',
                    prop: 'bankAccount',
                    valueType: 'text',
                },
                {
                    label: '开户行',
                    prop: 'bank',
                    valueType: 'text',
                },
                {
                    label: '账号',
                    prop: 'bankCardNo',
                    valueType: 'text',
                },
            ],
            title: '账户信息',
        },
        {
            columns: [
                {
                    label: '姓名',
                    prop: 'contactName',
                    valueType: 'text',
                },
                {
                    label: '手机号',
                    prop: 'contactMobile',
                    valueType: 'text',
                },
                {
                    label: '身份证号',
                    prop: 'contactIdCardNo',
                    valueType: 'text',
                },
            ],
            title: '认证联系信息',
        },

        {
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    label: '营业执照附件',
                    prop: 'businessLicenseAttachmentsList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '授权函',
                    prop: 'attachmentsAuthorizationLetterList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '资质文件',
                    prop: 'qualificationDocumentList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '项目业绩',
                    prop: 'projectPerformanceList',
                },
            ],
            title: '附件',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 8,
                    },
                    label: '附件',
                    prop: 'faceSignRecordList',
                    type: 'input',
                    valueType: '',
                },
            ],
            title: '面签记录',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 8,
                    },
                    label: '驳回原因',
                    prop: 'rejectReason',
                    type: 'textArea',
                    valueType: 'text',
                },
            ],
            title: '驳回原因',
            hideInGroup: !showReason.value,
        },
    ]
})

const showFileUpload = computed(() => [0].includes(data.value?.enterpriseAuditStatus))

function goBack() {
    back()
}

const dialogVisible = ref(false)
const rejectReason = ref('')

function submitAuth() {
    if (rejectReason.value && rejectReason.value.length > 0) {
        cancel()
    }
    else {
        ElMessage.error('请填写驳回原因')
    }
}
function showReasonDialog() {
    dialogVisible.value = true
    rejectReason.value = ''
}
function submit() {
    mutateClick(1)
}

function cancel() {
    mutateClick(2)
}

function mutateClick(auditStatus: 1 | 2) {
    // 1：审核通过，2：审核不通过
    const faceSignRecordList = cloneDeep(state.value.faceSignRecordList.map((item) => {
        return {
            fileName: item.name,
            fileUrl: item.url,
        }
    }))
    const params: any = {
        auditStatus,
        faceSignRecordList: auditStatus === 1 ? faceSignRecordList : [],
        jcEnterpriseNo: id.value,
    }
    console.log(params)
    if (auditStatus === 2 && rejectReason.value) {
        params.rejectReason = rejectReason.value
    }
    mutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            dialogVisible.value = false

            goBack()
        },
    })
}

watchEffect(() => {
    if (data.value) {
        const businessLicenseAttachmentsList = data.value.businessLicenseList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const attachmentsAuthorizationLetterList = data.value.authorizationLetterList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const qualificationDocumentList = data.value.qualificationDocumentList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const projectPerformanceList = data.value.projectPerformanceList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const faceSignRecordList = data.value.faceSignRecordList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        state.value = cloneDeep({
            ...data.value,
            attachmentsAuthorizationLetterList,
            businessLicenseAttachmentsList,
            faceSignRecordList,
            cat: data.value?.cat && JSON.parse(data.value?.cat),
            enterpriseSecondType: `${data.value?.enterpriseSecondType}`,
            logo: data.value?.logo || '',
            projectPerformanceList,
            qualificationDocumentList,
            supplyCat: data.value?.supplyCat ? JSON.parse(data.value?.supplyCat) : [],
        })
        key.value++
    }
})
</script>

<template>
    <ElSkeleton v-if="isLoading"
                :rows="5"
    />

    <ElCard v-else>
        <SearchForm v-model="state"
                    :group="finalGroup"
                    :has-footer="false"
                    class="mb-20"
        >
            <template #plus-field-logo>
                <FlUpload :key="key"
                          v-model="state.logo"
                          tips
                          accept=".jpg,.jpeg,.png"
                          :disabled="true"
                          is-mall-admin
                />
            </template>

            <template #plus-field-authenticationAmount>
                {{ authenticationAmountEunm[state?.isPaid] }}
            </template>

            <template #plus-field-businessLicenseAttachmentsList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload :key="key"
                              v-model="state.businessLicenseAttachmentsList"
                              list-type="text"
                              :limit="1"
                              :file-size="10"
                              :accept="fileType"
                              is-mall-admin
                              :disabled="disabled"
                              @success="changeBusinessLicenseAttachmentsList = true"
                    />

                    <div class="text-14 c-#86909C cursor-pointer">
                        最多上传一张
                    </div>
                </div>
            </template>

            <template #plus-field-attachmentsAuthorizationLetterList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload :key="key"
                              v-model="state.attachmentsAuthorizationLetterList"
                              list-type="text"
                              :limit="5"
                              :file-size="10"
                              :accept="fileType"
                              tips
                              is-mall-admin
                              :disabled="disabled"
                              @success="changeAttachmentsAuthorizationLetterList = true"
                    />

                    <div class="text-14 c-#86909C cursor-pointer"
                         @click="downTpl('授权函模板')"
                    >
                        <span class="c-#EA0000">下载</span>《授权函模板》
                    </div>
                </div>
            </template>

            <template #plus-field-qualificationDocumentList>
                <FlUpload :key="key"
                          v-model="state.qualificationDocumentList"
                          list-type="text"
                          :limit="5"
                          :file-size="10"
                          :accept="fileType"
                          tips
                          is-mall-admin
                          :disabled="disabled"
                />
            </template>

            <template #plus-field-projectPerformanceList>
                <FlUpload :key="key"
                          v-model="state.projectPerformanceList"
                          list-type="text"
                          :limit="5"
                          :file-size="10"
                          :accept="fileType"
                          tips
                          is-mall-admin
                          :disabled="disabled"
                />
            </template>

            <template #plus-field-faceSignRecordList>
                <FlUpload v-model="state.faceSignRecordList"
                          list-type="text"
                          :limit="10"
                          is-mall-admin
                          :file-size="10"
                          :disabled="!showFileUpload"
                />
            </template>
        </SearchForm>

        <div class="flex gap-10 justify-center">
            <ElButton @click="goBack">
                返回
            </ElButton>

            <template v-if="data?.enterpriseAuditStatus === 0">
                <ElButton :loading="isPending"
                          @click="showReasonDialog"
                >
                    驳回
                </ElButton>

                <ElButton type="primary"
                          :loading="isPending"
                          @click="submit"
                >
                    通过
                </ElButton>
            </template>
        </div>

        <ElDialog v-model="dialogVisible"
                  title="驳回原因"
                  width="800"
                  :destroy-on-close="true"
        >
            <div>
                <ElInput v-model="rejectReason"
                         type="textarea"
                         :rows="5"
                />
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <ElButton @click="dialogVisible = false">
                        取消
                    </ElButton>

                    <ElButton type="primary"
                              @click="submitAuth"
                    >
                        确认
                    </ElButton>
                </div>
            </template>
        </ElDialog>
    </ElCard>
</template>
